<?php

namespace App\Http\Controllers\Api\Goods;

use DB;

use Carbon\Carbon;

use App\Models\Goods\GoodsImport;  //导入商品表

use App\Models\Goods\GoodsSaleEdit;  //待发布商品表

use App\Models\Goods\GoodsStore;  //仓库商品表

use App\Models\Goods\WmsGoodsMaster;  //主商品库存表

use App\Models\Goods\GoodsMarktingStrategy; //商品营销策略表

use App\Models\Mall\MallMaster;  //门店主表

use App\Models\Bill\Bill;  //订单主表

use App\Models\ConfigureFunction;  //配置主表

use Illuminate\Http\Request;

use App\Http\Controllers\Controller;

class OutwardBatchController extends Controller
{

    /**
     * 批量新增商品接口
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function addProduct( Request $request )
    {

        $args_data = json_decode( $request->input('param') ,true );

        if ( empty( $args_data ) ) {
            return response()->json(['code' => 100001, 'message' => '参数错误']);
        }
        if ( count( $args_data ) > 1000 ) {
            return response()->json(['code' => 100002, 'message' => '每次最多1000条']);
        }

        $error_data = []; //错误信息

        $return_data = []; //返回信息

        $fail = 1; //错误行数

        foreach ( $args_data as $product ) {

            if ( !isset( $product['product_name'] ) || empty( $product['product_name'] ) ) {
                $error_data[] = [
                    'message' => '第'. $fail .' 行商品名称为空'
                ];
                $fail ++;
                continue;
            }

            if ( !isset( $product['product_code'] ) || empty( $product['product_code'] ) ) {
                $error_data[] = [
                    'message' => '第'. $fail .' 行商品编码为空'
                ];
                $return_data[] = [
                    'product_code' => $product['product_code']
                ];
                $fail ++;
                continue;

            }

            if ( !isset( $product['product_type'] ) || !ebsig_is_int( $product['product_type'] ) ) {

                $product['product_type'] = 1; //不传商品类型,默认为普通商品
            }

            if ( !isset( $product['market_price'] ) || empty( $product['market_price'] ) ) {
                $error_data[] = [
                    'message' => '第'. $fail .' 行市场价为空'
                ];
                $return_data[] = [
                    'product_code' => $product['product_code']
                ];
                $fail ++;
                continue;
            }

            if ( !isset( $product['sale_price'] ) || empty( $product['sale_price'] ) ) {
                $error_data[] = [
                    'message' => '第'. $fail .' 行销售价为空'
                ];
                $return_data[] = [
                    'product_code' => $product['product_code']
                ];
                $fail ++;
                continue;
            }

            //查询三级商品是否存在
            $goods_import = GoodsImport::select('importID')->where( ['product_code_str'=>$product['product_code'] ])->get()->toArray();
            if ( $goods_import ) {
                $error_data[] = [
                    'message' => '第'. $fail .' 行商品已经存在'
                ];
                $return_data[] = [
                    'product_code' => $product['product_code']
                ];
                $fail ++;
                continue;
            }

            //将格式化的价格写入到变量中
            $sale_price = sprintf("%1.2f", $product['sale_price']);  //市场价
            $market_price = sprintf("%1.2f", $product['market_price']); //销售价

            $cost_price = '0.00';       //成本价
            $higher_price = '0.00';     //最高价
            $lower_price = '0.00';      //最低价
            $brief = '';                //商品简述
            $sale_points = 0;          //可获积分
            $product_rate= '0.0000';   //商品税率(跨境商品)
            $record_price = '0.00';    //备案价(跨境商品)
            $record_code = '';          //备案号(跨境商品)
            $customs_product_code = ''; //海关商品编码（跨境商品）

            if ( !empty( $product['cost_price'] ) ) {
                $cost_price = sprintf("%1.2f", $product['cost_price']);
            }
            if ( !empty( $product['higher_price'] ) ) {
                $higher_price = sprintf("%1.2f", $product['higher_price']);
            }
            if ( !empty( $product['lower_price'] ) ) {
                $lower_price = sprintf("%1.2f", $product['lower_price']);
            }
            if ( isset( $product['brief'] ) && !empty( $product['brief'] ) ) {
                $brief = $product['brief'];
            }
            if ( isset( $product['sale_points'] ) && !empty( $product['sale_points'] ) ) {
                $sale_points = $product['sale_points'];
            }
            if ( !empty( $product['product_rate'] ) ) {
                $product_rate = sprintf("%1.4f", $product['product_rate']);
            }
            if ( !empty( $product['record_price'] ) ) {
                $record_price = sprintf("%1.2f", $product['record_price']);
            }
            if ( isset( $product['record_code'] ) && !empty( $product['record_code'] ) ) {
                $record_code = $product['record_code'];
            }
            if ( isset( $product['customs_product_code'] ) && !empty( $product['customs_product_code'] ) ) {
                $customs_product_code = $product['customs_product_code'];
            }

            $product_data = array(
                'mainPostID' => 0,
                'product_type' => $product['product_type'],
                'product_name' => $product['product_name'],
                'brand_name' => '',
                'unit_name' => '',
                'brief' => $brief,
                'pc_description' => '',
                'mobile_description' => '',
                'bigCategoryID' => 0,
                'midCategoryID' => 0,
                'smallCategoryID' => 0,
                'product_limit' => 0,
                'forsale_type' => 0,
                'supplier_id' => 1,
                'spec_type' => 0,
                'PC' => 1,
                'WAP' => 1,
                'APP' => 1,
                'sale' => array(
                    0 => array(
                        'product_code' => $product['product_code'],
                        'spec1' => '',
                        'spec2' => '',
                        'sale_price' => $sale_price,
                        'market_price' => $market_price,
                        'cost_price' => $cost_price,
                        'higher_price' => $higher_price,
                        'lower_price' => $lower_price,
                        'product_rate' => $product_rate,
                        'record_price' => $record_price,
                        'record_code' => $record_code,
                        'customs_product_code' => $customs_product_code,
                        'weight' => 0,
                        'sale_points' => $sale_points,
                        'product_spec' => '1.00'
                    )
                )
            );

            $product_import = GoodsImport::store( $product_data );
            if ( $product_import['code'] != 200 ) {
                $error_data[] = [
                    'message' => '第'. $fail .' 行' . $product_import['message']
                ];
                $return_data[] = [
                    'product_code' => $product['product_code']
                ];
                $fail ++;
                continue;
            }

            $fail ++;
        }

        $message = 'ok';
        if ( !empty( $error_data ) ) {
            $message = $error_data;
        }

        return response()->json(['code' => 200, 'message' => $message,'data' => $return_data]);
    }


    /**
     * 批量保存商品库存接口
     * @param Request $request
     * @return array|\Illuminate\Http\JsonResponse
     */
    public function storeStock( Request $request )
    {

        $args_data = json_decode( $request->input('param') ,true );

        if ( empty( $args_data ) ) {
            return response()->json(['code' => 100001, 'message' => '参数错误']);
        }
        if ( count( $args_data ) > 1000 ) {
            return response()->json(['code' => 100002, 'message' => '每次最多1000条']);
        }

        $product_data = []; //商品库存信息

        $error_data = []; //错误信息

        $return_data = []; //返回信息

        $fail = 1; //错误行数

        try {

            //开启事务
            DB::beginTransaction();

            foreach ( $args_data as &$stock ) {

                if ( !isset( $stock['product_code'] ) || empty( $stock['product_code'] ) ) {
                    $error_data[] = [
                        'message' => '第'. $fail .' 行商品编码为空'
                    ];
                    $fail ++;
                    continue;
                }
                if ( !isset( $stock['store_code'] ) || empty( $stock['store_code'] ) ) {
                    $error_data[] = [
                        'message' => '第'. $fail .' 行仓库编号为空'
                    ];
                    $fail ++;
                    continue;
                }
                if ( !isset( $stock['amount'] ) || !ebsig_is_int( $stock['amount'] ) ) {
                    $error_data[] = [
                        'message' => '第'. $fail .' 行可售库存格式不正确'
                    ];
                    $fail ++;
                    continue;
                }
                $amount = floor( $stock['amount'] );

                //是否开启门店选品
                $is_choose_goods_by_mall = ConfigureFunction::getConfigureField(8, 'is_choose_goods_by_mall');
                if ( $is_choose_goods_by_mall == 1 ) {

                    //检查仓库编号
                    $mall_master = MallMaster::select('mallID')->where( ['mallCode'=>$stock['store_code'] ] )->get()->toArray();
                    if ( !$mall_master ) {
                        $error_data[] = [
                            'message' => '第'. $fail .' 行仓库编号【'.$stock['store_code'].'】不存在'
                        ];
                        $return_data[] = [
                            'store_code' => $stock['store_code'],
                            'product_code' => $stock['product_code']
                        ];
                        $fail ++;
                        continue;
                    }

                    $storeID = $mall_master[0]['mallID'];

                } else {

                    $storeID = 1;
                }

                //检查商品编码
                $goods_sale_edit = GoodsSaleEdit::select('mainPostID','goodsName','forsale')->where( ['product_code'=> $stock['product_code'] ] )->get()->toArray();
                if ( !$goods_sale_edit ) {
                    $error_data[] = [
                        'message' => '第'. $fail .' 行商品编码【'.$stock['product_code'].'】不存在'
                    ];
                    $return_data[] = [
                        'store_code' => $stock['store_code'],
                        'product_code' => $stock['product_code']
                    ];
                    $fail ++;
                    continue;
                }

                //查询商品仓库信息
                $goods_store = GoodsStore::select('storeID')->where( ['product_code' => $stock['product_code'],'sync_offline_stock'=>0 ])->first();
                if ( $goods_store ) {
                    $fail ++;
                    continue;
                }

                //查询商品已销售数量
                $customer_buy_amount = Bill::join("bill_goods","bill_master.bill_no",'=','bill_goods.bill_no')
                    ->where( 'bill_goods.product_code', '=', $stock['product_code'] )
                    ->whereIn( 'bill_master.bill_status',[1,3] )
                    ->sum('bill_goods.goods_amount');

                if ( $customer_buy_amount ) {
                    $amount = $amount - $customer_buy_amount;
                    if ( $amount <= 0 ) {
                        $amount = 0;
                    }
                }

                //防止重复保存商品库存信息
                if ( !in_array( $goods_sale_edit[0]['mainPostID'],$product_data ) ) {

                    $product_data[] = $goods_sale_edit[0]['mainPostID'];

                    //保存主商品库存信息
                    $product_master_obj = new WmsGoodsMaster;
                    $product_master_obj->uuid = makeUuid();
                    $product_master_obj->timeStamp = Carbon::now();
                    $product_master_obj->creator = 'api';
                    $product_master_obj->createTime = Carbon::now();
                    $product_master_obj->storeID = $storeID;
                    $product_master_obj->mainPostID = $goods_sale_edit[0]['mainPostID'];
                    $product_master_obj->save();

                }

                //查询商品仓库,存在则更新商品仓库,不存在则插入商品仓库信息
                $product_store = GoodsStore::select('storeID')->where( ['product_code'=>$stock['product_code']] )->first();

                if ( !$product_store ) {

                    //保存商品仓库详细信息
                    $product_store_obj = new GoodsStore;
                    $product_store_obj->uuid = makeUuid();
                    $product_store_obj->timeStamp = Carbon::now();
                    $product_store_obj->creator = 'api';
                    $product_store_obj->createTime = Carbon::now();
                    $product_store_obj->mainPostID = $goods_sale_edit[0]['mainPostID'];
                    $product_store_obj->storeID = $storeID;
                    $product_store_obj->product_code = $stock['product_code'];
                    $product_store_obj->goodsName = $goods_sale_edit[0]['goodsName'];
                    $product_store_obj->enableSaleAmount = $amount;
                    $product_store_obj->forsale = $goods_sale_edit[0]['forsale'];
                    $product_store_obj->save();
                } else {

                    GoodsStore::where(['product_code'=>$stock['product_code']])
                        ->update(['storeID'=>$storeID,'enableSaleAmount'=>$amount]);
                }

                $fail ++;
            }

            DB::commit();

            $message = 'ok';
            if ( !empty( $error_data ) ) {
                $message = $error_data;
            }

        } catch (\Exception $e) {

            DB::rollBack();

            return response()->json(['code' => 100003, 'message' => '批量保存商品库存失败']);
        }


        return response()->json(['code' => 200, 'message' => $message, 'data' => $return_data]);
    }


    /**
     * 批量更新商品价格接口
     * @param Request $request
     * @return array|\Illuminate\Http\JsonResponse
     */
    public function updatePrice( Request $request )
    {

        $args_data = json_decode( $request->input('param') ,true );

        if ( empty( $args_data ) ) {
            return response()->json(['code' => 100001, 'message' => '参数错误']);
        }
        if ( count( $args_data ) > 1000 ) {
            return response()->json(['code' => 100002, 'message' => '每次最多1000条']);
        }

        $error_data = []; //错误信息

        $return_data = []; //返回信息

        $fail = 1; //错误行数

        try {

            //开启事务
            DB::beginTransaction();

            foreach ( $args_data as &$price ) {

                if ( !isset( $price['store_code'] ) || empty( $price['store_code'] ) ) {
                    $error_data[] = [
                        'message' => '第'. $fail .' 行仓库编号为空'
                    ];
                    $fail ++;
                    continue;
                }
                if ( !isset( $price['product_code'] ) || empty( $price['product_code'] ) ) {
                    $error_data[] = [
                        'message' => '第'. $fail .' 行商品编码为空'
                    ];
                    $fail ++;
                    continue;
                }
                if ( !isset( $price['market_price'] ) || empty( $price['market_price'] ) ) {
                    $error_data[] = [
                        'message' => '第'. $fail .' 行市场价为空'
                    ];
                    $fail ++;
                    continue;
                }
                if ( !isset( $price['sale_price'] ) || empty( $price['sale_price'] ) ) {
                    $error_data[] = [
                        'message' => '第'. $fail .' 行销售价为空'
                    ];
                    $fail ++;
                    continue;
                }
                if ( $price['sale_price'] > $price['market_price'] ) {
                    $error_data[] = [
                        'message' => '第'. $fail .' 行销售价大于市场价'
                    ];
                    $fail ++;
                    continue;
                }

                //是否开启门店选品
                $is_choose_goods_by_mall = ConfigureFunction::getConfigureField(8, 'is_choose_goods_by_mall');
                if ( $is_choose_goods_by_mall == 1 ) {

                    //检查仓库编号
                    $mall_master = MallMaster::select('mallID')->where( ['mallCode'=>$price['store_code'] ] )->get()->toArray();
                    if ( !$mall_master ) {
                        $error_data[] = [
                            'message' => '第'. $fail .' 行仓库编号【'.$price['store_code'].'】不存在'
                        ];
                        $return_data[] = [
                            'store_code' => $price['store_code'],
                            'product_code' => $price['product_code']
                        ];
                        $fail ++;
                        continue;
                    }

                    $storeID = $mall_master[0]['mallID'];

                } else {

                    $storeID = 1;
                }

                //检查商品编码
                $goods_sale_edit = GoodsSaleEdit::where( ['product_code'=> $price['product_code'] ] )->get()->toArray();
                if ( !$goods_sale_edit ) {
                    $error_data[] = [
                        'message' => '第'. $fail .' 行商品编码【'.$price['product_code'].'】不存在'
                    ];
                    $return_data[] = [
                        'store_code' => $price['store_code'],
                        'product_code' => $price['product_code']
                    ];
                    $fail ++;
                    continue;
                }

                //查询商品,存在则更新商品价格,不存在则插入商品信息
                $goods_markting = GoodsMarktingStrategy::select('shop_id')->where( ['postID'=>$goods_sale_edit[0]['postID']] )->first();

                if ( !$goods_markting ) {

                    //保存商品营销策略表信息
                    $product_markting_obj = new GoodsMarktingStrategy;
                    $product_markting_obj->uuid = makeUuid();
                    $product_markting_obj->timeStamp = Carbon::now();
                    $product_markting_obj->creator = 'api';
                    $product_markting_obj->createTime = Carbon::now();
                    $product_markting_obj->mainPostID = $goods_sale_edit[0]['mainPostID'];
                    $product_markting_obj->shop_id = $storeID;
                    $product_markting_obj->postID = $goods_sale_edit[0]['postID'];
                    $product_markting_obj->product_code = $price['product_code'];
                    $product_markting_obj->product_spec = $goods_sale_edit[0]['spec'];
                    $product_markting_obj->goodsName = $goods_sale_edit[0]['goodsName'];
                    $product_markting_obj->marketPrice = $price['market_price'];
                    $product_markting_obj->salePrice = $price['sale_price'];
                    $product_markting_obj->salePoints = $goods_sale_edit[0]['salePoints'];
                    $product_markting_obj->save();
                } else {

                    GoodsMarktingStrategy::where(['postID'=>$goods_sale_edit[0]['postID']])
                            ->update(['marketPrice'=>$price['market_price'],'salePrice'=>$price['sale_price']]);
                }

                $fail ++;

            }

            DB::commit();

            $message = 'ok';
            if ( !empty( $error_data ) ) {
                $message = $error_data;
            }

        } catch (\Exception $e) {

            DB::rollBack();

            return response()->json(['code' => 100003, 'message' => '批量更新商品价格失败']);
        }


        return response()->json(['code' => 200, 'message' => $message,'data' => $return_data]);
    }

}